/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ziroom.crm.mq.core.init;

import com.ziroom.crm.mq.core.spi.SpiLoader;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Load registered init functions and execute in order.
 */
@Slf4j
public final class InitExecutor {

    private static final AtomicBoolean INITIALIZED = new AtomicBoolean(false);

    /**
     * 静态初始化
     * The initialization will be executed only once.
     */
    public static void doInit() {
        if (!INITIALIZED.compareAndSet(false, true)) {
            return;
        }
        try {
            List<InitFunc> initFuncList = SpiLoader.loadPrototypeInstanceListSorted(InitFunc.class);
            for (InitFunc initFunc : initFuncList) {
                initFunc.init();
                log.info(String.format("[crm-mq] Executing %s", initFunc.getClass().getCanonicalName()));
            }
        } catch (Exception ex) {
            log.warn("[crm-mq] WARN: Initialization failed", ex);
            ex.printStackTrace();
        } catch (Error error) {
            log.warn("[crm-mq] ERROR: Initialization failed with fatal error", error);
            error.printStackTrace();
        }
    }

    private InitExecutor() {
    }
}
